﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UpdateApp
{
    public partial class HandleFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder result = new StringBuilder();

            //DataTable dt = ExcelByNPOI.ExcelToData(@"C:\Users\Ning\Desktop\工作簿1.xlsx", "", 0);

            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    foreach (DataRow item in dt.Rows)
            //    {
            //        Dictionary<string, string> dic = new Dictionary<string, string>();

            //        dic.Add("productBatchNO", item[0].ToString());
            //        dic.Add("barCodeList", item[1].ToString());

            //        result += Common.Request("http://zs.dzpj.com/BarCode/Post", dic, null, "POST")+"</br>";
            //    }
            //}

            string file = Request["file"] != null ? Path.Combine(FileHelper.GetUploadPath(), DateTime.Now.ToString("yyyy-MM-dd"), Request["file"] + ".txt") : "";

            if (file != "")
            {
                //需上传的批次号 为空则上传全部
                string batchNo = Request["batch"] != null ? Request["batch"] : "";

                string[] strs = File.ReadAllLines(file, Encoding.UTF8);

                foreach (string str in strs)
                {
                    if (str.IndexOf(".txt") < 0)
                        continue;

                    string batch = str.Substring(str.IndexOf("DP"), str.LastIndexOf(".") - str.IndexOf("DP"));
                    string barCode = str.Substring(str.LastIndexOf(":") + 1, str.Length - str.LastIndexOf(":") - 1);

                    if (batchNo != "" && batchNo != batch)
                        continue;

                    Dictionary<string, string> dic = new Dictionary<string, string>();

                    dic.Add("productBatchNO", batch);
                    dic.Add("barCodeList", barCode);

                    result.Append(RequestData("http://zs.dzpj.com/BarCode/Post", dic, null, "POST") + "</br>");
                }
            }
            else
                result.Append( "参数：?file=文件名&batch=批次号");

            Response.Write(result);
        }

        /// <summary>
        /// 发送请求 返回结果
        /// JObject jo = (JObject)JsonConvert.DeserializeObject(result)
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="obj">请求数据</param>
        /// <param name="values">请求参数 Method ContentType Encoding</param>
        /// <returns></returns>
        public string RequestData(string url, object obj, Dictionary<string, string> headers, params string[] values)
        {
            string result = "";

            values = values.Length == 0 ? new string[1] { "GET" } : values;

            Dictionary<string, string> dic = obj as Dictionary<string, string>;
            StringBuilder builder = new StringBuilder();

            if (dic != null)
            {
                foreach (string item in dic.Keys)
                    builder.AppendFormat("{0}={1}&", item, dic[item]);

                if (values[0].ToUpper() == "GET")
                {
                    url = url + "?" + builder.ToString();

                    url = url.EndsWith("&") ? url.Remove(url.Length - 1) : url;
                }
            }
            else
            {
                builder.Append(JsonConvert.SerializeObject(obj));
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Method = values[0];
            req.ContentType = values.Length > 1 ? values[1] : "application/x-www-form-urlencoded";
            Encoding coding = values.Length > 2 ? Encoding.GetEncoding(values[2]) : Encoding.UTF8;

            if (headers != null)
                foreach (string item in headers.Keys)
                    req.Headers.Add(item, headers[item]);

            if (builder.Length > 0 && values[0].ToUpper() != "GET")
            {
                byte[] data = coding.GetBytes(builder.ToString());
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();

            //响应结果 
            using (StreamReader reader = new StreamReader(stream, coding))
            {
                result = reader.ReadToEnd();
            }

            return result;

        }
    }
}